class Solution(object):
    def maxDistance(self, grid):
        m = len(grid)
        n = len(grid[0])
        dist = 0
        now = set()
        for i in range(m):
            for j in range(n):
                if grid[i][j] == 1:
                    now.add((i, j))
        while now:
            next_set = set()
            for x, y in now:
                for ux, uy in [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]:
                    if 0 <= ux < m and 0 <= uy < n and grid[ux][uy] == 0:
                        grid[ux][uy] = 2
                        next_set.add((ux, uy))
            if next_set:
                dist += 1
            now = next_set
        if not dist:
            return - 1
        else:
            return dist


